<?php

namespace App\Console\Commands;

use App\Models\GrGood;
use App\Models\GrRefund;
use App\Models\GrUser;
use App\Models\Orders;
use App\service\ReturnService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class Order extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'order';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        //查询未支付的订单
        $data = Orders::where('is_pay', 0)->where('order_status', '<>', 3)->get()->toArray();
        foreach ($data as $k => $v) {
            //判断订单超过半小时为支付的订单
            if (time() - strtotime($v['created_at']) >= 60 * 30) {
                DB::beginTransaction();
                try {
                    //修改订单状态，为超时支付
                    $res = Orders::where('id', $v['id'])->update(['order_status' => 3]);
                    if ($res) {
                        //查询关于此订单的商品
                        $orderGoodsData = \App\Models\OrderGoods::where('order_id', $v['id'])->get()->toArray();
                        foreach ($orderGoodsData as $k => $v) {
                            $goods = GrGood::where('goods_id', $v['goods_id'])->first();
                            //恢复库存
                            $result = GrGood::where('goods_id',  $v['goods_id'])->update(['stock_total' => $goods->stock_total + $v['goods_number']]);
                        }
                    }
                    DB::commit();
                    if ($result) {
                       Log::info("订单超时未支付，修改成功");
                    } else {
                        Log::info("订单超时未支付，修改失败");
                    }
                } catch (\Exception $e) {
                    //回滚事务
                    Db::rollback();
                }


            }
        }
    }
}
